package com.epro.dx.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.order.OrderDetailActivity;
import com.epro.dx.adapter.ProductListAdapter;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.task.GetProductsFromSkusAsyncTask;
import com.epro.dx.task.GetRecommendTask;
import com.epro.dx.task.GetRecommendTask.GetRecommendsModel;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.epro.dx.widget.MyGridView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.model.ProductModel;

import java.util.ArrayList;

/**
 * 支付完成页面
 * @author hf
 *
 */
public class PaymentCompleteActivity extends BaseFragmentActivity implements
		OnClickListener {
	private static final String TAG ="PaymentCompleteActivity";
	private ImageView payMethodLogoLeft;
	private ImageView payMethodLogoRight;
	private TextView orderNumberTv;
	private TextView payMoney;
	private Button orderDetails;
	private Button continueShoppings;
	
	private String orderNumber;
	
	private String money;
	
	private String cardType;
	
	private String payMethod;
	
	private int payStatus;
	private String errorCode;
	private LinearLayout bfdProductsLayout;
	private MyGridView bfdProductList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Tracker tracker = DXApplication.getContext().getTracker(
				TrackerName.APP_TRACKER);
		tracker.setScreenName(AboutUsActivity.class.getSimpleName());
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
		// 设置窗体无标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_payment_complete);
		setTitleContent(R.string.title_checkout);
		Intent intent=getIntent();
		if(null==intent){
			finish();
			return;
		}
		getData(intent);
		intView();
		setListenner();
		//获取推荐商品
		getRecommandProducts();
	}
	
	/**
	 * @创建：Tony 2016-5-31下午2:23:40
	 * @描述：获取推荐商品
	 */
	private void getRecommandProducts() {
	    AsyncTaskUtil.executeTask(new GetRecommendTask(ActivityUtil.getCustomerID(), 3, new MyAsyncTaskListenner() {
            
            @Override
            public void onPreTask() {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void onPostTask(String result, Object obj) {

                //解析数据获取sku列表
                GetRecommendsModel model =(GetRecommendsModel) obj;
                if(model.IsSuccess && model.Skus!=null){
                    ArrayList<Integer> skus = new ArrayList<Integer>();
                    String[] splits = model.Skus.split(",");
                    for (int i = 0; i < splits.length; i++) {
                        skus.add(Integer.parseInt(splits[i]));
                    }
                    
                    if(skus.size()>0){
                        AsyncTaskUtil.executeTask(new GetProductsFromSkusAsyncTask(skus,PaymentCompleteActivity.this,0,60,Constant.SORT_POPULARITY, -2, OnekeyFilterLocalUtil.getFilterState(PaymentCompleteActivity.this), new MyAsyncTaskListenner() {
                            
                            @Override
                            public void onPreTask() {
                            }
                            
                            @SuppressWarnings("unchecked")
                            @Override
                            public void onPostTask(String result, Object bfdProducts) {
                                if("0".equals(result)&& bfdProducts!=null && ((ArrayList<ProductModel>)bfdProducts).size()>0){
                                    //显示推荐商品列表
                                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
                                    bfdProductsLayout.setVisibility(View.VISIBLE);
                                    ProductListAdapter productListAdapter = new ProductListAdapter(PaymentCompleteActivity.this, ((ArrayList<ProductModel>)bfdProducts), false, getDensityDpi(),theTracker);
                                    productListAdapter.setCurrencyCode(((ArrayList<ProductModel>)bfdProducts).get(0).getCurrencyCode(), ((ArrayList<ProductModel>)bfdProducts).get(0).getCurrencyCodeSymbol());
                                    productListAdapter.setRecommendRequestId("");
                                    bfdProductList.setAdapter(productListAdapter);
                                }
                                else{
                                    //隐藏推荐列表
                                    bfdProductsLayout.setVisibility(View.GONE);
                                }
                            }
                        }));
                    }
                }
            
            }
        }));
	}

	/**
	 * 获取页面传递数据
	 * @param intent
	 */
	private void getData(Intent intent){
		orderNumber = intent.getStringExtra("orderNumber");
		money = intent.getStringExtra("payMoney");
		cardType = intent.getStringExtra("cardType");
		payMethod=intent.getStringExtra("payMethod");
		payStatus = intent.getIntExtra("payStatus", -1);
		errorCode = intent.getStringExtra("errorCode");
	}

	/**
	 * 初始化数据
	 */
	private void intView() {
		payMethodLogoLeft = (ImageView) findViewById(R.id.pay_method_logo_left);
		payMethodLogoRight = (ImageView) findViewById(R.id.pay_method_logo_right);
		orderNumberTv = (TextView) findViewById(R.id.pay_order_number);
		payMoney = (TextView) findViewById(R.id.pay_money);
		orderDetails = (Button) findViewById(R.id.payment_complete_order_details_btn);
		continueShoppings = (Button) findViewById(R.id.payment_complete_continue_shopping_btn);
		
		bfdProductsLayout = (LinearLayout) findViewById(R.id.payment_complete_bfd);
		bfdProductList = (MyGridView) findViewById(R.id.bfd_product_list);
		setPayMethodLogo();
		setInfoText();
	}

	/**
	 * 设置页面显示文本
	 */
	private void setInfoText() {

		orderNumberTv.setText(this.getString(R.string.payment_complete_order_number, orderNumber));
		//设置显示数据
		switch (payStatus) {
		case ServerConstant.ReturnCode.CreditCard.CREDITCARD_PAYSTATUS_SUCCESS:
			//支付成功
			payMoney.setTextColor(Color.rgb(86, 126, 67));
			payMoney.setText(this.getString(R.string.payment_complete_paid_sug, money));
			break;
		case ServerConstant.ReturnCode.CreditCard.CREDITCARD_PAYSTATUS_FAILED:
			//支付失败
			payMoney.setTextColor(Color.rgb(230, 95, 94));
			if(null!=errorCode && (ServerConstant.ReturnCode.CreditCard.CREDITCARD_PAY_ERROR001.equals(errorCode)
					||ServerConstant.ReturnCode.CreditCard.CREDITCARD_PAY_ERROR002.equals(errorCode)
					||ServerConstant.ReturnCode.CreditCard.CREDITCARD_PAY_ERROR003.equals(errorCode))){
				payMoney.setText(this.getString(R.string.payment_complete_abnormal));
			}else{
				payMoney.setText(this.getString(R.string.payment_complete_failed));
			}
			break;
		case ServerConstant.ReturnCode.CreditCard.CREDITCARD_PAYSTATUS_PROCCESSING:
			//支付处理中
			payMoney.setTextColor(Color.rgb(86, 126, 67));
			payMoney.setText(this.getString(R.string.payment_complete_processing));
			break;

		default:
			break;
		}
	}

	/**
	 * 设置监听事件
	 * 
	 */
	private void setListenner() {
		orderDetails.setOnClickListener(this);
		continueShoppings.setOnClickListener(this);
	}
	
	/**
	 * 设置支付方式Logo
	 */
	private void setPayMethodLogo(){
		if("Paypal".equals(payMethod)){
			payMethodLogoLeft.setBackgroundResource(R.drawable.add_address_bg);
			payMethodLogoRight.setBackgroundResource(R.drawable.add_address_bg);
		}else if("CreditCard".equals(payMethod)){
			int resId=ActivityUtil.getCardTypeResId(cardType);
			payMethodLogoLeft.setBackgroundResource(resId);
			payMethodLogoRight.setBackgroundResource(resId);
		}else{
			payMethodLogoLeft.setBackgroundResource(R.drawable.add_address_bg);
			payMethodLogoRight.setBackgroundResource(R.drawable.add_address_bg);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.payment_complete_order_details_btn:
			goToOrderDetail(orderNumber);
			break;
		case R.id.payment_complete_continue_shopping_btn:
			goToHome();
			break;

		default:
			break;
		}
	}
	
	/**
	 * 进入订单详情
	 * @param orderNumber 订单号
	 */
	private void goToOrderDetail(String orderNumber) {
		if (null == orderNumber) {
			finish();
			return;
		}
		// 单击后进入详情
		Intent intent = new Intent(this, OrderDetailActivity.class);
		Bundle b = new Bundle();
		b.putString("OrderNumber", orderNumber);
		b.putString(ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
				ServerConstant.ActionConstant.ACTION_CHECKOUT);
		// b.putSerializable("orderItemModel", orderItemModel);
		intent.putExtras(b);
		startActivity(intent);
		finish();
	}

	/**
	 * 回到首页
	 */
	private void goToHome() {
		Intent intent = new Intent();
		intent.setClass(this, HomeActivity.class);
		intent.putExtra(HomeActivity.CURRENT_TAB_TAG,
				getString(HomeActivity.titleArray[0]));
		startActivity(intent);
		finish();
	}
	
}
